layui.use(["table", "layer", "form"], function () {
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    $("#searchBtn").on("click", function () {
        table.render({
            elem: "#userTable",
            url: "/menus/page",
            page: true,
            limit: 5,
            limits: [5, 10, 15, 20],
            where: {username: $("#searchName").val()},
            cols: [[
                {title: '菜单名', field: 'name', width: '15%', align: "center"},
                {title: '地址', field: 'url', width: '15%', align: "center"},
                {title: '上级', field: 'parentName', width: '15%', align: "center"},
                {title: '操作', width: '25%', align: "center", toolbar: "#operateTemplate"}
            ]]
        });
        //数据表操作事件
        table.on('tool(userTable1)', function (obj) {
            //点击删除按钮事件
            if (obj.event == "del") {
                layer.confirm("你确定要删除该菜单吗？", function () {
                    $.post("/menus/del?id=" + obj.data.id, function () {
                        layer.closeAll();
                        $("#searchBtn").click();
                    });
                }, function () {
                });
            }
            //点击编辑按钮事件
            if (obj.event == "edit") {
                $.get("/menus/tops", function (tops) {
                    var options = "";
                    $.each(tops, function (i, v) {
                        options += "<option value = '" + v.id + "'>" + v.name + "</option>";
                    });
                    $.get("/menus/" + obj.data.id, function (ret) {
                        layer.open({
                            type: 1,
                            title: "编辑菜单",
                            content: $("#userFormTemplate").html(),
                            area: ['500px', '400px']
                        });
                        $("#parentId").append(options);
                        form.val("userForm", ret);
                    });
                });
            }
        });
    }).click();
    //给新增按钮绑定点击事件
    $("#addBtn").on("click", function () {
        $.get("/menus/tops", function (ret) {
            var options = "";
            $.each(ret, function (i, v) {
                options += "<option value = '" + v.id + "'>" + v.name + "</option>";
            });
            layer.open({
                type: 1,
                title: "新增菜单",
                content: $("#userFormTemplate").html(),
                area: ['500px', '400px'],
                success: function () {
                    $("#parentId").append(options);
                    form.render();
                }
            });
        });

    });
    //弹出窗口中保存按钮绑定事件
    $("body").on("click", "#saveBtn", function () {
        $.post("/menus/save", form.val("userForm"), function () {
            layer.closeAll();
            $("#searchBtn").click();
        });
    });


});